package org.raymond.icloud.common.core.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;

public class RSAUtils {
    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.set("username", "123");
        json.set("password", "123");
        String str = json.toString();
        System.out.println("json:"+str);
        str = DigestUtil.sha256Hex(str);

        String result = test02(str);
        if(str.equals(result)){
            System.out.println("success");
        }else{
            System.out.println("failed");
        }
    }

    public static String test01(String input){
        RSA rsa = new RSA();
        String pub = rsa.getPublicKeyBase64();
        String pri = rsa.getPrivateKeyBase64();
        String enc = rsa.encryptBase64(input, KeyType.PublicKey);
        String result = rsa.decryptStr(enc, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
        return result;
    }

    public static String test02(String input){
        RSA rsa = new RSA();
        String pub = rsa.getPublicKeyBase64();
        String pri = rsa.getPrivateKeyBase64();
        String enc = rsa.encryptBase64(input, KeyType.PublicKey);
        byte[] dec = rsa.decrypt(enc, KeyType.PrivateKey);
        String result = StrUtil.str(dec, CharsetUtil.CHARSET_UTF_8);
        return result;
    }

    public static String test03(String input){
        RSA rsa = new RSA();
        String pub = rsa.getPublicKeyBase64();
        String pri = rsa.getPrivateKeyBase64();
        byte[] enc = rsa.encrypt(input, KeyType.PublicKey);
        String encStr = HexUtil.encodeHexStr(enc);
        byte[] rbyte = rsa.decrypt(encStr, KeyType.PrivateKey);
        String result = StrUtil.str(rbyte, CharsetUtil.CHARSET_UTF_8);
        return result;
    }

    public static String test04(String input){
        RSA rsa = new RSA();
        String pub = rsa.getPublicKeyBase64();
        String pri = rsa.getPrivateKeyBase64();
        String encBase64 = rsa.encryptBase64(input, KeyType.PublicKey);
        byte[] rbyte = rsa.decrypt(encBase64, KeyType.PrivateKey);
        String result = StrUtil.str(rbyte, CharsetUtil.CHARSET_UTF_8);
        return result;
    }
}
